package com.ss.tools;

import java.security.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DateUtils {

    private static final Logger logger = LoggerFactory.getLogger(DateUtils.class);


    private static final String DATE_PATTERN = "(((0[1-9]|[12][0-9]|3[01])/((0[13578]|1[02]))|((0[1-9]|[12][0-9]|30)/(0[469]|11))|(0[1-9]|[1][0-9]|2[0-8])/(02))/([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3}))|(29/02/(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00)))";


    public static final long ONE_DAY_LONG = 86400000L;


    public static final String YYYYMMDD = "yyyyMMdd";


    public static boolean isDate(String str) {
        Pattern pattern = Pattern.compile(
                "(((0[1-9]|[12][0-9]|3[01])/((0[13578]|1[02]))|((0[1-9]|[12][0-9]|30)/(0[469]|11))|(0[1-9]|[1][0-9]|2[0-8])/(02))/([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3}))|(29/02/(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00)))");
        return pattern.matcher(str).matches();
    }


    public static long getCurrentTime() {
        return System.currentTimeMillis();
    }


    public static String timestamp2String(Timestamp time, String pattern) {
        return DateFormatUtils.format(time.getTimestamp(), pattern);
    }


    public static String formatDate(Date date, String pattern) {
        return DateFormatUtils.format(date, pattern);
    }


    public static Date formatDate(String date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            logger.error("日期格式转换失败", e);

            return null;
        }
    }


    public static Date defaultFormat(String str) {
        return formatDate(str, "yyyyMMdd");
    }


    public static int defaultFormat(Date date) {
        return Integer.valueOf(formatDate(date, "yyyyMMdd")).intValue();
    }


    public static int defaultFormat(long millis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        return defaultFormat(cal.getTime());
    }


    public static String parseTimestamp(Timestamp time) {
        return parseDate(time.getTimestamp());
    }


    public static String parseDate(Date date) {
        return formatDate(date, "yyyyMMdd");
    }


    public static int getYear() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        return cal.get(1);
    }

}
